<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示消息 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>

      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="+activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs 区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTagLeave" @tab-click="onTabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器区域 -->
              <el-cascader v-model="cascaderValue" :options="catelist" :props="cascaderProps" @change="onCascaderChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item, i) in manyData" :key="item.attr_id">
              <!-- 复选框的容器 -->
              <el-checkbox-group v-model="item.attr_vals">
                <!-- 每个可选项 -->
                <el-checkbox :label="option" v-for="(option, i) in item.options" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item, i) in onlyData" :key="i">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传组件 -->
            <el-upload :action="uploadURL" :headers="uploadHeaders" list-type="picture-card" :auto-upload="true" :on-success="onUploadSuccess" :file-list="fileList">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="previewDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>

            <el-button type="primary" class="btn-add" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
const regNumber = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/

export default {
  data() {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        pics: [],
        goods_introduce: ''
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          {
            pattern: regNumber,
            message: '商品价格必须是大于0的整数或小数',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          {
            pattern: regNumber,
            message: '商品重量必须是大于0的整数或小数',
            trigger: 'blur'
          }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          {
            pattern: /^\d{1,}$/,
            message: '商品数量必须是大于0的整数',
            trigger: 'blur'
          }
        ],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      catelist: [],
      cascaderValue: [],
      cascaderProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      previewDialogVisible: false,
      dialogImageUrl: '',
      disabled: false,
      // 上传图片的 URL 地址
      uploadURL: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      // 上传组件的 Headers 请求头
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token') || ''
      },
      fileList: []
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    cateId() {
      return this.cascaderValue.length === 3 ? this.cascaderValue[2] : null
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      this.catelist = res.data
    },
    onCascaderChange() {
      this.manyData = []
      this.onlyData = []
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.addForm.goods_cat = ''
        this.$message.warning('只能选择三级商品分类！')
        return
      }
      this.addForm.goods_cat = this.cascaderValue.join(',')
    },
    beforeTagLeave() {
      if (this.activeIndex === '0' && this.cascaderValue.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    async onTabClick() {
      // 动态参数
      if (this.activeIndex === '1') {
        if (this.manyData.length !== 0) return
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })

        if (res.meta.status !== 200) return this.$message.error('获取分类参数失败！')

        // 处理复选框的可选项以及选中的 Value 值
        res.data.forEach(item => {
          const attrString = item.attr_vals
          if (attrString.trim().length === 0) {
            item.attr_vals = []
            item.options = []
          } else {
            item.attr_vals = attrString.split(',')
            item.options = attrString.split(',')
          }
        })

        // 将动态参数保存到 manyData 中
        this.manyData = res.data
      } else if (this.activeIndex === '2') {
        if (this.onlyData.length !== 0) return
        // 静态属性
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })

        if (res.meta.status !== 200) return this.$message.error('获取静态属性失败！')

        this.onlyData = res.data
        console.log(this.onlyData)
      }
    },
    // 点击预览图片按钮时的回调函数
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.previewDialogVisible = true
    },
    // 点击了移除按钮时的回调函数
    handleRemove(file) {
      this.fileList = this.fileList.filter(x => x.uid !== file.uid)
      this.addForm.pics = this.addForm.pics.filter(x => x.pic !== file.response.data.tmp_path)
    },
    // 上传成功的回调函数
    onUploadSuccess(response, file, fileList) {
      if (response.meta.status !== 200) return this.$message.error('上传图片失败！')

      this.fileList = fileList
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(this.addForm.pics)
    },
    // 添加商品
    addGoods() {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请完善商品信息后再添加商品！')

        const attrs = []
        // 处理动态参数
        this.manyData.forEach(manyItem => {
          const manyInfo = {
            attr_id: manyItem.attr_id,
            attr_value: manyItem.attr_vals.join(',')
          }
          attrs.push(manyInfo)
        })
        // 处理静态属性
        this.onlyData.forEach(onlyItem => {
          const onlyInfo = {
            attr_id: onlyItem.attr_id,
            attr_value: onlyItem.attr_vals
          }
          attrs.push(onlyInfo)
        })

        // 准备表单的参数对象
        const fd = { ...this.addForm, attrs }

        // 发起请求，添加新商品
        // 注意：商品的名称不允许重复
        const { data: res } = await this.$http.post('goods', fd)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')

        this.$message.success('添加商品成功！')
        // 重定向到商品列表页面
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}

/deep/ .el-step__title {
  font-size: 12px;
}

/deep/ .el-step__icon {
  font-size: 12px;
}

.el-checkbox {
  margin: 5px 10px 5px 0px !important;
}

/deep/ .ql-editor {
  min-height: 300px;
}

.btn-add {
  margin-top: 15px;
}
</style>
